package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static com.bodacn.keypoint.MainApplication.TermNo;

public class OutputActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG=this.getClass().getName();
    private final int MSG_DetailOver=1001;
    private final int MSG_HeadOver =1002;
    private final int MSG_GetDetail=1003;
    private  final int MSG_ERRMSG = 1004;
    private final int MSG_PackListOver =1005;
    private final int MSG_ManuTXM=1006;

    String STORE_NAME = "Settings";
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID;
    String QueryTitle,QueryType;
    Button btn_UpDate,btn_DownDate,btn_Return;
    ListView queryList, packList;
    TextView txt_Title;
    EditText edt_WorkDate;
    JSONArray detailJson,headJson, packListJson;
    Toast curToast;

    String selOrderNo="",selStyleNo="",selStyleSort="",NeedOrder="";
    LinearLayout querylisthead;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_output);
        hideBottomUIMenu();
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo","");
        curLoginUser=paramBundle.getString("LoginUser","");
        curDepartNo=paramBundle.getString("CurDepartNo","");
        curDepart=paramBundle.getString("CurDepart","");
        curServiceUrl=paramBundle.getString("ServiceUrl","");
        curServiceDir=paramBundle.getString("ServiceDir","");
        QueryType=paramBundle.getString("QueryType","MUTI");
        NeedOrder=paramBundle.getString("NeedOrder","NO");
        CPUID=paramBundle.getString("CPUID");
        //界面信息
        QueryTitle=paramBundle.getString("QueryTitle");
        System.out.println(paramBundle);
        //初始化界面
        txt_Title=findViewById(R.id.txt_Title);
        txt_Title.setText(QueryTitle);
        btn_UpDate=findViewById(R.id.btn_UpDate);
        btn_UpDate.setOnClickListener(this);
        btn_DownDate=findViewById(R.id.btn_DownDate);
        btn_DownDate.setOnClickListener(this);
        btn_Return=findViewById(R.id.btn_Return);
        btn_Return.setOnClickListener(this);
        queryList =findViewById(R.id.queryList);
        queryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (detailJson.optJSONObject(position).has("DBH")) {
                    try {
                        GetPacklist(detailJson.optJSONObject(position).getString("DBH"),detailJson.optJSONObject(position).getString("PO"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        packList =findViewById(R.id.packList);
        findViewById(R.id.btn_refresh).setOnClickListener(this);
        //列表头;
        querylisthead=findViewById(R.id.querylisthead);
        //文本框
        edt_WorkDate = findViewById(R.id.edt_WorkDate);
        edt_WorkDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(v.getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,"完成",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edt_WorkDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                        GetDetail(QueryType);
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle("选择查询起始日期");
                mDialog.show();

            }
        });
        edt_WorkDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("edit_startDate","onFocusChange");
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        SharedPreferences settings = this.getSharedPreferences(STORE_NAME, getApplicationContext().MODE_PRIVATE);
        String dateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
        edt_WorkDate.setText(dateStr);
        //初始提醒;
        curToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
    public  String TransValue(String params)
    {
        if (params.toUpperCase().equals("NULL")||params.equals("0")||params.equals("0.0"))
            return "";
        else return params;
    }

    //字符串加减天数
    private String StringToDate(String time,int AddDays) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date= null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        System.out.println(date);
        c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, AddDays);// 今天+1天
        Date tmpDate = c.getTime();
        System.out.println(tmpDate);
        String s = format.format(tmpDate);
        return s;
    }
    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_UpDate:
                edt_WorkDate.setText(StringToDate(edt_WorkDate.getText().toString(),-1));
                GetDetail(QueryType);
                break;
            case R.id.btn_DownDate:
                edt_WorkDate.setText(StringToDate(edt_WorkDate.getText().toString(),1));
                GetDetail(QueryType);
                break;
            case R.id.btn_Return:
                finish();
                break;
            case R.id.btn_refresh:
                //发消息查明细;
                Message msg = new Message();
                msg.what = MSG_GetDetail;
                handler.removeMessages(msg.what);
                handler.sendMessage(msg);
                break;
            default:
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        GetHeadList(QueryType);
    }

    //获取明细;
    private void GetPacklist(String paramDBH,String paramPO) {
        try {
            packListJson = new JSONArray("[]");
            //显示明细数据
            PackListAdapter callListAdapter=new PackListAdapter(getApplicationContext());
            packList.setAdapter(callListAdapter);
        } catch (Exception e){
            e.printStackTrace();
        }
        String sqlCmd="Exec KeyPoint_GetPackList @OperType='PackList',@DepartNo='"+curDepartNo+"',@DBH='"+paramDBH+"',@PO='"+paramPO+"',@TermNo='"+TermNo
                +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlCmd);

    }
    //获取明细;
    private void GetDetail(String paramType) {
        try {
            detailJson = new JSONArray("[]");
            //显示明细数据
            DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
            queryList.setAdapter(detailListAdapter);
        } catch (Exception e){
            e.printStackTrace();
        }
        String sqlCmd="Exec KeyPoint_OutputQuery @OperType='Query',@QueryTitle='"+QueryTitle+"',@QueryType='"+paramType+"',@WorkDate='"+edt_WorkDate.getText().toString()
                    +"',@DepartNo='"+curDepartNo+"',@TermNo='"+TermNo +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlCmd);

    }

    //提交所选择的工序至服务器,然后刷新工序列表;
    private void GetHeadList(final String paramType) {
        try {
            headJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Runnable run = new Runnable() {
            @Override
            public void run() {
                //将数据读到JSONArray;
                try {
                    String sqlcmd="Exec KeyPoint_OutputQuery @OperType='Title',@QueryType='"+paramType+"',@QueryTitle='"+QueryTitle
                            +"',@DepartNo='"+curDepartNo+"',@TermNo='"+TermNo+"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
                    Statement stmt = DBUtil.getSQLConnection().createStatement();
                    ResultSet rs = stmt.executeQuery(sqlcmd);
                    //取字段相关信息;
                    ResultSetMetaData metaData = rs.getMetaData();
                    int columnCount = metaData.getColumnCount();
                    //遍列数据;
                    while (rs.next()) {
                        JSONObject jsonObj = new JSONObject();
                        // 遍历每一列
                        for (int i = 1; i <= columnCount; i++) {
                            String columnName = metaData.getColumnLabel(i);
                            Object value = rs.getObject(columnName);
                            if (value==null) value="";
                            jsonObj.put(columnName, value);
                        }
                        headJson.put(jsonObj);
                    }
                    //显示预排单;
                    Message msg = new Message();
                    msg.what = MSG_HeadOver;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                    //消息给创建列;
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }


            }
        };
        new Thread(run).start();
    }

    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJson != null) && (headJson.length() > 0)) {
            int childCount = querylisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = querylisthead.getChildAt(i);
                if ((view instanceof TextView)||(view instanceof View)) {
                    querylisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            System.out.println(headJson);
            for (int i=0;i<headJson.length();i++)
                if (headJson.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJson.optJSONObject(i).getString("TitleName");
                        TitleText = headJson.optJSONObject(i).getString("TitleText");
                        TxtSize = headJson.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJson.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJson.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(this);
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.text_main));
                        tv.setTextSize(TxtSize);
                        if (headJson.optJSONObject(i).has("Align")==true) {
                            Align = headJson.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJson.optJSONObject(i).has("TitleColor")==true){
                            tv.setTextColor(GetColorValue( headJson.optJSONObject(i).getString("TitleColor")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) querylisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else querylisthead.addView(tv);
                        //增加间隔线
                        if (i<headJson.length()-1) {
                            View lineView = new View(this);
                            lineView.setBackgroundColor(getResources().getColor(R.color.gridLine));
                            querylisthead.addView(lineView, new LinearLayout.LayoutParams(1, MATCH_PARENT, 0));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            querylisthead.postInvalidate();
            //发消息查明细;
            Message msg = new Message();
            msg.what = MSG_GetDetail;
            handler.removeMessages(msg.what);
            handler.sendMessage(msg);
        }
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData ( final String SQLComm){
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    String OperType="";
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OperType")==true)  OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true)  OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        //呼叫信息及库存警告
                        if (OperType.equals("Query") == true) {
                            detailJson = jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_DetailOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OperType.equals("PackList") == true) {
                            packListJson = jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_PackListOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }

                        if (OperType.equals("ManuTxm") == true) {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ManuTXM;
                            Bundle bundle=new Bundle();
                            if (jsonArray.optJSONObject(0).has("ResultInfo")) bundle.putString("MSG",jsonArray.optJSONObject(0).getString("ResultInfo"));
                            if (jsonArray.optJSONObject(0).has("TXM")) bundle.putString("TXM",jsonArray.optJSONObject(0).getString("TXM"));
                            if (jsonArray.optJSONObject(0).has("Result")) bundle.putString("Result",jsonArray.optJSONObject(0).getString("Result"));
                            msg.setData(bundle);
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                            return;
                        }
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                            return;
                        }
                    } else{
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("MSG","未返回数据");
                        msg.setData(bundle);
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();

    }



    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_ERRMSG:
                    Bundle bundle=msg.getData();
                    new AlertDialog.Builder(querylisthead.getContext())
                            .setTitle(getString(R.string.SystemHint)).setMessage(bundle.getString("MSG"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).create().show();
                    break;
                case MSG_ManuTXM:
                    Bundle bundle1=msg.getData();
                    String MSG=bundle1.getString("MSG","");
                    String TXM=bundle1.getString("TXM","");
                    String Result=bundle1.getString("Result","");
                    if (TXM.length()>0 && Result.equals("Y")){
                        for (int i=0;i<packListJson.length();i++){
                            try {
                                if (packListJson.optJSONObject(i).has("TXM")&&packListJson.optJSONObject(i).has("Allow"))
                                if (TXM.equals(packListJson.optJSONObject(i).getString("TXM"))){
                                    packListJson.optJSONObject(i).put("Allow","N");
                                    ((BaseAdapter)packList.getAdapter()).notifyDataSetChanged();
                                    return;
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        if (MSG.length()>0) {
                            new AlertDialog.Builder(querylisthead.getContext())
                                    .setTitle(getString(R.string.SystemHint)).setMessage(MSG)
                                    .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    }).create().show();
                        }
                    }
                    break;
                case MSG_HeadOver:
                    //创建列;
                    CreateListHead();
                    break;
                case MSG_GetDetail:
                    GetDetail(QueryType);
                    break;
                case MSG_PackListOver:
                    //显示明细数据
                    PackListAdapter packListAdapter=new PackListAdapter(getApplicationContext());
                    packList.setAdapter(packListAdapter);
                    break;
                case MSG_DetailOver:
                    //显示明细数据
                    DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
                    queryList.setAdapter(detailListAdapter);
                    break;
                default:
                    break;
            }
        }
    };

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    //自定义适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_query_listhead, null, false);
            //if (convertView == null) convertView = inflater.inflate(R.layout.activity_query_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            int pullVatListHeight=parent.getHeight();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,(pullVatListHeight/12)));
            int color = getResources().getColor(R.color.text_black);
            int backcolor = getResources().getColor(R.color.content);
            if (position%2==0) view.setBackgroundColor(backcolor);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (detailJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = detailJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                for (int i = 0; i < headJson.length(); i++)
                    if (headJson.optJSONObject(i).has("TitleText") == true) {
                        try {
                            String TitleName = headJson.optJSONObject(i).getString("TitleName");
                            if (detailJson.optJSONObject(position).has(TitleName)==true) tmpValue= detailJson.optJSONObject(position).getString(TitleName);
                            else tmpValue="unReturn";
                            int TxtSize = headJson.optJSONObject(i).getInt("TxtSize");
                            float txtWidth = headJson.optJSONObject(i).getLong("TxtWidth");
                            int AutoZoom = headJson.optJSONObject(i).getInt("AutoZoom");
                            TextView tv = new TextView(view.getContext());
                            tv.setText(tmpValue);
                            tv.setWidth((int) txtWidth);
                            tv.setTextColor(color);
                            tv.setGravity(Gravity.CENTER_VERTICAL);
                            if (headJson.optJSONObject(i).has("Align")==true) {
                                int Align;
                                Align = headJson.optJSONObject(i).getInt("Align");
                                switch (Align) {
                                    case 0:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                        break;
                                    case 1:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                        break;
                                    case 2:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                        break;
                                    default:
                                        tv.setGravity(Gravity.CENTER_VERTICAL);
                                        break;
                                }
                            }
                            //自定义文字颜色;
                            if (headJson.optJSONObject(i).has("Color")==true){
                                tv.setTextColor(GetColorValue( headJson.optJSONObject(i).getString("Color")));
                            }
                            //自定负数是红色;
                            if ((headJson.optJSONObject(i).has("NgvColor")==true)&&(headJson.optJSONObject(i).has("NgvTrans")==true)){
                                if (headJson.optJSONObject(i).getString("NgvTrans").equals("YES")&&(isNumer(tmpValue)==true)){
                                    if (Float.valueOf(tmpValue)<0) tv.setTextColor(GetColorValue(headJson.optJSONObject(i).getString("NgvColor")));
                                }
                            }
                            tv.setTextSize(TxtSize);
                            //添加到View中;
                            if (AutoZoom == 1)
                                ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                            else ((LinearLayout)view).addView(tv);
                            //增加间隔线
                            if (i<headJson.length()-1) {
                                View lineView = new View(view.getContext());
                                lineView.setBackgroundColor(getResources().getColor(R.color.gridLine));
                                ((LinearLayout)view).addView(lineView, new LinearLayout.LayoutParams(1, MATCH_PARENT, 0));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailListAdapter_position:"+position);
            return view;
        }
    }


    //员工状态表格适配器;
    public final class PackListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public PackListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return packListJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return packListJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View  conView = inflater.inflate(R.layout.activity_output_packitem, null, false);
            int pullVatListWidth=parent.getWidth();
            int pullVatListHeight=parent.getHeight();
            conView.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,(pullVatListHeight/12)));
            ViewHolder holder =new ViewHolder();
            holder.btn_enter = conView.findViewById(R.id.btn_enter);
            conView.setTag(holder);
            holder.btn_enter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String txm="";
                    try {
                        if (packListJson.optJSONObject(position).has("TXM")==true) txm=packListJson.optJSONObject(position).getString("TXM");
                        ManuInputTxm(txm);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            int textColor=getResources().getColor(R.color.text_black);
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (packListJson.optJSONObject(position).has("ConColor")){
                    textColor=GetColorValue(packListJson.optJSONObject(position).getString("ConColor"));
                }
                TextView tv = (TextView) conView.findViewById(R.id.txt_PackNo);// 显示文字
                if (packListJson.optJSONObject(position).has("PackNo"))
                    tv.setText(packListJson.optJSONObject(position).get("PackNo").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_Number);// 显示文字
                if (packListJson.optJSONObject(position).has("Number"))
                    tv.setText(packListJson.optJSONObject(position).get("Number").toString());
                tv.setTextColor(textColor);
                if (packListJson.optJSONObject(position).has("Allow")){
                    if (packListJson.optJSONObject(position).getString("Allow").equals("Y")) {
                        holder.btn_enter.setBackground(getResources().getDrawable(R.drawable.btn_selector_green));
                        holder.btn_enter.setEnabled(true);
                    }
                    else {
                        holder.btn_enter.setBackground(getResources().getDrawable(R.drawable.btn_selector_dimgray));
                        holder.btn_enter.setEnabled(false);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg","OrderGridAdapter_position:"+position);
            return conView;
        }

        //提取出来方便点
        public final class ViewHolder {
            public Button btn_enter;
        }
    }

    //手工补录;
    private void ManuInputTxm(String txm) {
        String sqlCmd="Exec KeyPoint_ManuTXM @OperType='ManuTXM',@DepartNo='"+curDepartNo+"',@TXM='"+txm+"',@TermNo='"+TermNo +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlCmd);
    }


}
